<?php
/**
 * 《产品信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Mold.class.php 1053 2010-04-07 11:15:15Z sunxy $
 */
require_once(dirname(__FILE__) . '/MoldUtil.class.php');

class Mold extends MoldUtil {
	public $tbl = Constant::tbl_mold;

	public $status = array(
		'-' => '请选择',
		'1' => '等待审核',
		'2' => '等待生产',
		'3' => '正在生产',
		'4' => '完成生产',
	
		'8' => '取消',	
		'9' => '其它',
	);
	
	public $orderby = array(
		'-' => '请选择',
		'customer' => '客户',
		'code' => '编号',
		'supplier' => '供应商',
	
		'emp' => '负责人',
		'engineer' => '工程师',
	
		'status' => '状态',	
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'customer' => '客户',
		'category' => '分类',
	
		'emp' => '业务员',
		'engineer' => '工程师',
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);	

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('category_option', $this->category);
	}
	
	function mobile($controller, $request) {
		$this->pretreat($controller);
	
		global $CategoryTree;
	
		$data = $CategoryTree['产品管理'];
	
		$ret = array();
		foreach ($data as $k => $v) {
			if ($this->tree_my($v)) {
				$ret[$k] = $v;
			}
		}
	
		$controller->assign('menu', $ret);
	
		$controller->display($request, 'mobile');
		return true;
	}
	
	function tab($controller, $request) {		
		$data = array(
			'产品信息' => array('cc'=>'mold.php?do=Mold.view_code', 'js'=>''),
			'产品管理' => array('cc'=>'mold.php?do=Mold.find', 'js'=>'1'),
				
			'产品资料' => array('cc'=>'mold.php?do=Reference.find', 'js'=>'1'),
					
			// '跟模信息' => array('cc'=>'mold.php?do=Info.find', 'js'=>''),
			// '生产计划' => array('cc'=>'mold.php?do=Plan.find', 'js'=>''),
			// '产品外发' => array('cc'=>'mold.php?do=Outer.find', 'js'=>''),
			
			'外发加工' => array('cc'=>'mold.php?do=Process.find', 'js'=>'1'),
			'零件检测' => array('cc'=>'mold.php?do=Testing.find', 'js'=>'1'),
		
			'注塑需求' => array('cc'=>'zs.php?do=Requirement.find', 'js'=>'1'),
			// '注塑安排' => array('cc'=>'zs.php?do=Plan.find', 'js'=>''),
		
			'货运需求' => array('cc'=>'express.php?do=Requirement.find', 'js'=>'1'),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}
	
	function view_code($controller, $request) {
		$this->pretreat($controller);
	
		$controller->display($request, 'mold/mold/code');
		return true;
	}
	
	function view_codePost($controller, $request) {
		
		$code_s = $request['code_s'];
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a WHERE code = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code_s);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			
			if (!$this->_view_code_my($row)) {
				$controller->assign('msg', "对不起，操作受限，请联系管理员。");
					
				$controller->display($request, 'info');
				return true;
			}
			
			$row = $this->_view($row['id']);
			
			$controller->assign_by_ref('result', $row);
			
			$ret = $this->_view_tab();
			
			$controller->assign_by_ref('tabs', $ret);
			
			$controller->display($request, 'mold/mold/view');
		}
		
		return true;
	}
	
	function _view_code_my($data) {
		
		if ($this->_is_admin()) {
			return true;
		}
		
		if ($this->_audit('25') || $this->_audit('76')) {
			return true;
		}
		
		$emp = $_SESSION['id'];
				
		if ($data['emp'] == $emp || $data['engineer'] == $emp || $data['oper'] == $emp) {
			return true;
		}
		
		return false;
	
	}
	
	function _view_tab() {
		$data = array(
			'每日工作' => array('cc'=>'mold.php?do=Work.view_mold&id=', 'js'=>'1'),
	
			'任务信息' => array('cc'=>'mold.php?do=Plan.view_mold&id=', 'js'=>'1'),
			// '跟模信息' => array('cc'=>'mold.php?do=Work.view_mold&id=', 'js'=>'1'),
	
			'外发加工' => array('cc'=>'mold.php?do=ProcessItem.view_mold&id=', 'js'=>'1'),
	
			'物料申请' => array('cc'=>'material.php?do=Bom.view_mold&id=', 'js'=>'1'),
			'物料领用' => array('cc'=>'material.php?do=Out.view_mold&id=', 'js'=>'1'),
	
			'零件检测' => array('cc'=>'mold.php?do=Testing.view_mold&id=', 'js'=>'1'),
			'货运信息' => array('cc'=>'express.php?do=Requirement.view_mold&id=', 'js'=>'1'),
			'注塑信息' => array('cc'=>'zs.php?do=Requirement.view_mold&id=', 'js'=>'1'),
				
			'收入信息' => array('cc'=>'finance.php?do=In.view_mold&id=', 'js'=>'1'),
			'支出信息' => array('cc'=>'finance.php?do=Out.view_mold&id=', 'js'=>'1'),
			
			'附件信息' => array('cc'=>'mold.php?do=Mold.view_file&id=', 'js'=>'1'),
		);
		
		return $this->_tab2($data);
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-2 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '业务员',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'mold/mold/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == '`join`') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['join'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		return "visible = 1";
	}

	function _where($request) {
		$code_s = $request['code_s'];
		
		$category_s = $request['category_s'];
		
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];
		
		$outer_s = $request['outer_s'];
		$engineer_s = $this->_input($request['engineer_s']);
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}

		if (!empty($code_s)) {
			$where .= " AND code = '" . $code_s . "'";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}
		
		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}

		if (!empty($outer_s) && $outer_s <> '-') {
			$where .= " AND `outer` = '" . $outer_s . "'";
		}

		if (!empty($engineer_s) && $engineer_s <> '-') {
			$where .= " AND engineer = '" . $engineer_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);
				
				$row['color'] = $this->_status_color($row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->assign('emp', $_SESSION['id']);

		$controller->display($request, 'mold/mold/list');
		return true;
	}
	
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'mold/mold/list');
		return true;
	}
	
	function _status_color($row) {
		$status = $row['status'];

		// if ($status > 8 || $row['outer'] == '2') {
		if ($status > 8) {
			return '';
		}

		$b1 = time() > strtotime($row['date']) ? true : false;
		
		if ($b1) {
			if ($status < 4) {
				return 'red';
			} else {
				return 'yellow';
			}
		}

		return '';
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);
		
		$controller->assign('t1', strtotime('28 day'));

		$id = $request['id'];
		if (empty($id)) {
			$controller->display($request, 'mold/mold/add_2');
			return true;
		}
		
		$controller->assign_by_ref('quote', $this->_view_quote($id));

		$controller->display($request, 'mold/mold/add');
		return true;
	}
	
	function _view_quote($id) {
		require_once(dirname(__FILE__) . '/../customer/Quote.class.php');
		$quote = new Quote();
		
		return $quote->_view($id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$customer = $this->_input($request['customer']);

		$code = $request['code'];
		$project = $this->_project($code);
		
		$category = $request['category'];
		$date = $request['date'];
		$content = addslashes($request['content']);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, dept, emp, date, customer, project, code, category, content, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $date, $customer, $project, $code, $category, $content, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);

		$request['id_s'] = $db->insert_id();
		
		if (!empty($id)) {
			$this->_status(Constant::tbl_quote, $id, 9);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'mold/mold/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$customer = $this->_input($request['customer']);
		$date = $request['date'];
		
		$code = $this->_input($request['code']);
		$project = $this->_project($code);
		
		$category = $request['category'];
		
		$engineer = $this->_input($request['engineer']);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$sm = $request['sm'];
		$content = addslashes($request['content']);
		$status = $request['status'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET office = '%s', dept = '%s', emp = '%s', date = '%s', customer = '%s', project = '%s', code = '%s', category = '%s', ";
		$fmt .= "supplier = '%s', supplier_x = '%s', sm = '%s', content = '%s', engineer = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $date, $customer, $project, $code, $category, $supplier, $supplier_x, $sm, $content, $engineer, $status, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function copy($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
		$row = $this->_view($id);
	
		$controller->assign_by_ref('result', $row);
	
		$controller->display($request, 'mold/mold/copy');
		return true;
	}
	
	function outer($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$controller->display($request, 'mold/mold/outer');
		return true;
	}
	
	function outerPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$engineer = $this->_input($request['engineer']);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$amount = $request['amount'];
		$currency = $request['currency'];
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$content = addslashes($request['content']);

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET supplier = '%s', supplier_x = '%s', amount = '%s', currency = '%s', rate = '%s', rmb = '%s', content = '%s', ";
		$fmt .= "engineer = '%s', status = '2', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $supplier_x, $amount, $currency, $rate, $rmb, $content, $engineer, $id);
		// debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function delete($controller, $request) {
		$this->pretreat($controller);

		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
			
			$this->_delete3($id);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2 WHERE id = '%s'";
		}
		
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($this->_audit('72')) {
			return true;
		}

		if ($row['emp'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$ret = $this->_view_tab();
		
		$controller->assign_by_ref('tabs', $ret);

		$controller->display($request, 'mold/mold/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['customer_t'] = Name::customer_code($row['customer']);
		$row['category_t'] = $this->category[$row['category']];
		$row['supplier_x'] = json_decode($row['supplier_x']);
		
		$row['engineer_t'] = Name::emp($row['engineer']);
		
		$row['files'] = $this->_files($row['id']);
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _is_engineer($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($this->_audit('72')) {
			return true;
		}

		if ($row['engineer'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function report($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);

		$row['category'] = $this->category[$row['category']];

		$row['emp_t'] = Name::emp($row['emp']);
		$row['engineer_t'] = Name::emp($row['engineer']);

		$row['outer_t'] = $this->outer[$row['outer']];

		$row['status_t'] = $this->status[$row['status']];

		$controller->assign_by_ref('result', $row);

		if ($row['outer'] == '2') {
			$controller->display($request, 'mold/mold/view');
			return true;
		}

		$controller->assign_by_ref('plan', $this->_report_plan($id));
		$controller->assign_by_ref('produce', $this->_report_produce($id));
		$controller->assign_by_ref('quality', $this->_report_quality($id));

		$controller->display($request, 'mold/mold/report');
		return true;
	}

	function _report_plan($id) {
		require_once 'Plan.class.php';
		$plan = new Plan();

		return $plan->_report_status($id);
	}

	function _report_produce($id) {
		require_once 'Produce.class.php';
		$produce = new Produce();

		return $produce->_report_status($id);
	}

	function _report_quality($id) {
		require_once 'Quality.class.php';
		$quality = new Quality();

		return $quality->_report_status($id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function p($controller, $request) {
		$this->pretreat($controller);

		$data = array();

		while (list($k, $v) = each($this->technics)) {
			if ($k == '-') {
				continue;
			}

			$row = array();
			$row['technics'] = $v;

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'mold/mold/p');
		return true;
	}

	function cc($a, $b) {
		return $a + $b;
	}
	
	function ajax_mold($controller, $request) {
		$mold = $request['mold'];
		
		debug($mold);
		
		$row = $this->code($this->tbl, $mold);
		if ($row['outer'] == '1') {
			$supplier = '2';
		} else {
			$db = newdb($this->dsn_r);
			$fmt = "SELECT * FROM %s WHERE mold = '%s'";
			$sql = sprintf($fmt, Constant::tbl_mold_outer, $row['id']);
			debug($sql);
			$result = $db->query($sql);
			$outer = $db->fetch_array($result);
			
			$supplier = $outer['supplier'];
		}
		
		$a = $this->id(Constant::tbl_supplier, $supplier);
		
		$row['supplier'] = $supplier;
		$row['supplier_t'] = $a['name'];
		
		debug(print_r($row, true));
		
		echo json_encode($row);
	}
	
	function ajax_my($controller, $request) {
		$data = $this->_ajax_code($request, '2');
		echo json_encode($data);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_code($controller, $request) {
		
		$data = $this->_ajax_code($request);
		echo json_encode($data);
	}

	function _ajax_code($request, $my = '1') {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		if ($my == '2') {
			$key = sprintf("%s_%s_%s_%s", $this->tbl, "code_my", $_SESSION['id'], $q);
		} else {
			$key = sprintf("%s_%s_%s", $this->tbl, "code_all", $q);
		}
		
		// $key = sprintf("%s_code_%s", $this->tbl, $q);
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		// $fmt = "SELECT * FROM %s WHERE visible = 1 AND code LIKE '%s' ORDER BY id DESC LIMIT %s";
		// $sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $n);
		
		if ($my == '2') {
			$fmt = "SELECT * FROM %s WHERE visible = 1 AND code LIKE '%s' AND (emp = '%s' OR engineer = '%s') ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $_SESSION['id'], $_SESSION['id'], $n);
		} else {
			$fmt = "SELECT * FROM %s WHERE visible = 1 AND code LIKE '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $n);
		}
		
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}
	
	function ajax_project($controller, $request) {
	
		$data = $this->_ajax_project($request);
		echo json_encode($data);
	}
	
	function _ajax_project($request, $my = '1') {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
	
		if ($my == '2') {
			$key = sprintf("%s_%s_%s_%s", $this->tbl, "project_my", $_SESSION['id'], $q);
		} else {
			$key = sprintf("%s_%s_%s", $this->tbl, "project_all", $q);
		}
	
		// $key = sprintf("%s_code_%s", $this->tbl, $q);
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}
	
		$db = newdb($this->dsn_r);
		// $fmt = "SELECT * FROM %s WHERE visible = 1 AND code LIKE '%s' ORDER BY id DESC LIMIT %s";
		// $sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $n);
	
		if ($my == '2') {
		$fmt = "SELECT DISTINCT project FROM %s WHERE visible = 1 AND code LIKE '%s' AND (emp = '%s' OR engineer = '%s') ORDER BY id DESC LIMIT %s";
				$sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $_SESSION['id'], $_SESSION['id'], $n);
		} else {
			$fmt = "SELECT DISTINCT project FROM %s WHERE visible = 1 AND code LIKE '%s' ORDER BY id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $n);
		}

		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$ret[] = $row;
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$controller->assign('t1', strtotime('-1 month'));

		$controller->display($request, 'mold/mold/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'customer');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'customer') {
			$row['a'] = sprintf("%s [%s]", Name::customer($row['a']), Name::customer_code($row['a']));
		} elseif ($px == 'category') {
			$row['a'] = $this->category[$row['a']];
		} elseif ($px == '`outer`') {
			$row['a'] = $this->outer[$row['a']];
		} elseif ($px == 'emp' || $px == 'engineer') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	/**
	 * 定时运行，每小时运行一次
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function aa($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s where status > 1 and status < 16";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$id = $row['id'];
			$status = $row['status'];

			$ss = $this->_ss($id, $status);
			if (empty($ss)) {
				continue;
			}

			$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $ss, $id);
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}

	function _ss($id, $status) {
		if ($status == 2 && $this->_status_2($id)) {
			return '3';
		}

		if ($status == 3 && $this->_status_2($id)) {
			return '4';
		}

		if ($status == 4 && $this->_status_4($id)) {
			return '5';
		}

		if ($status == 5 && $this->_status_5($id)) {
			return '6';
		}

		if ($status == 6 && $this->_status_6($id)) {
			return '7';
		}

		if ($status == 7 && $this->_status_7($id)) {
			return '8';
		}

		return '';
	}

	function _status_2($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s'";
		$sql = sprintf($fmt, Constant::tbl_mold_plan, $mold);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	function _status_3($mold) {
		$dd = date("'Y-m-d H:i:s'", strtotime('-3 day'));

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s' AND createtime > '%s'";
		$sql = sprintf($fmt, Constant::tbl_mold_plan, $mold, $dd);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return false;
		}

		return true;
	}

	function _status_4($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s'";
		$sql = sprintf($fmt, Constant::tbl_mold_produce, $mold);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	function _status_5($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s' AND status < 3";
		$sql = sprintf($fmt, Constant::tbl_mold_plan, $mold);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return false;
		}

		return true;
	}

	function _status_6($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s'";
		$sql = sprintf($fmt, Constant::tbl_mold_quality, $mold);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	function _status_7($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE mold = '%s' AND status < 4";
		$sql = sprintf($fmt, Constant::tbl_mold_produce, $mold);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return false;
		}

		return true;
	}

	function ajax_b($controller, $request) {
		$id = $_COOKIE['id_'];
		$data = array();
		if (!$this->_ajax_emp($id)) {
			$data['status'] = 2;
		} else {
			$data['status'] = 1;
		}

		$controller->assign('result', json_encode($data));

		$request['tpl'] = 'json';
		$controller->display($request, 'json');
		return true;
	}

	/**
	 * 定时运行，每小时运行一次
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function report_daily($controller, $request) {
		$this->pretreat($controller);

		$request['tpl'] = "html4";

		require_once 'Plan.class.php';
		$plan = new Plan();

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `outer` = '1' AND status > 2 AND status < 9 AND createtime > '2010-02-01'";
		$sql = sprintf($fmt, $this->tbl);
		// debug($sql);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$request['id'] = $row['id'];

			$plan->report_daily($controller, $request);
		}

		logdate($controller, $request);
		return true;
	}

	/**
	 * 导入
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function import($controller, $request) {
		$this->pretreat($controller);

		$type = array(
			'-' => '请选择',
			'1' => '文本方式',
			'2' => '文件方式',
		);

		$controller->assign_by_ref('import_option', $type);

		$controller->display($request, 'kq/record/import');
		return true;
	}

	function ajax_upload($controller, $request) {
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		if ($file->isValid()) {
			$filename = $file->upload['tmp_name'];
			debug($filename);

			$this->_xls($filename);
		}

		echo "1";
		return true;
	}

	/**
	 * 导入考勤信息
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function z($controller, $request) {
		$file = "d:/kqrecord1.xls";
		$file = "/home/sunxy/mold.xls";
		$this->_xls($file);

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}

	function _xls($file) {
		require_once APP_LIB . 'excel_class.php';

		Read_Excel_File($file, $return);
		// debug(print_r($return, true));

		$buf = $return['Sheet1'];

		$db = newdb($this->dsn_w);
		for($j = 1; $j < count($buf); $j++) {
			$a = $buf[$j];

			// print_r($a);

			$name = $a[0];
			if ($this->_xls_exist($name)) {
				continue;
			}

			$emp = $this->_xls_emp($name);
			if (!$emp) {
				continue;
			}

			$content = '补加数据，孙晓晔添加';

			$fmt = "INSERT INTO %s(name, content, emp, createtime, modifytime) VALUES('%s', '%s', '%s', NOW(), NOW())";
			$sql = sprintf($fmt, $this->tbl, $name, $content, $emp);
			// debug($sql);
			$db->query($sql);
		}
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function importPost($controller, $request) {
		$this->pretreat($controller);

		$aa = preg_split("/[\\n]+/i", $request['data']);

		$db = newdb($this->dsn_w);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}

			$name = $buf;

			if ($this->_xls_exist($name)) {
				continue;
			}

			$emp = $this->_xls_emp($name);
			if (!$emp) {
				continue;
			}

			$content = '补加数据，孙晓晔添加';

			$fmt = "INSERT INTO %s(name, content, emp, createtime, modifytime) VALUES('%s', '%s', '%s', NOW(), NOW())";
			$sql = sprintf($fmt, $this->tbl, $name, $content, $emp);
			// debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _xls_exist($mold) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE name = '%s'";
		$sql = sprintf($fmt, $this->tbl, $mold);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	function _xls_emp($mold) {
		$a = preg_split("/[\\s,|\.]+/", $mold);

		$db = newdb(Constant::tbl_customer);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, Constant::tbl_customer, $a[0]);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			$row = $db->fetch_array($result);

			return $row['emp'];
		}

		return false;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function move_engineer($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET engineer = '%s' WHERE engineer = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function move_id($customer, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE customer = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $customer);
		debug($sql);
		$db->query($sql);
	}
	
	function update_customer($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$fmt = "SELECT * FROM %s WHERE customer = 0";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$customer = $this->_customer($row['code']);
			$fmt = "UPDATE %s SET customer = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $customer, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _customer($s) {
		$c = preg_split("/[\.,]+/", $s);
		
		$row = Common::code(Constant::tbl_customer, $c[0]);
		
		return $row['id'];
	}
	
	function ajax_emp($controller, $request) {
		$id = $_COOKIE['id_'];
		$ret = array();
		
		if ($this->_ajax_x($id, 'engineer')) {
			$ret['status'] = 1;
		} elseif ($this->_ajax_x($id, 'emp')) {
			$ret['status'] = 1;
		} else if ($this->_ajax_x($id, 'oper')) {
			$ret['status'] = 1;
		} else {
			$ret['status'] = 2;
		}

		echo json_encode($ret);
	}
	
	function ajax_engineer($controller, $request) {
		$id = $_COOKIE['id_'];
		$ret = array();
		
		if ($this->_ajax_x($id, 'engineer')) {
			$ret['status'] = 1;
		} else if ($this->_is_admin() || $_SESSION['id'] == '102') {
			$ret['status'] = 1;
		} else {
			$ret['status'] = 2;
		}

		echo json_encode($ret);
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('342');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			// echo "222";
			return false;
		}

		$from = $this->email;
		$subject = '产品信息';
		
		$cc = array(	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'id DESC'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'id DESC'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}

		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'mold/mold/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('342');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$this->pretreat($controller);

		$from = $this->email;
		$subject = '产品信息（周报）';
		
		$cc = array(	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'id DESC'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'id DESC'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'mold/mold/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'emp';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, COUNT(id) AS c FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, COUNT(id) AS c FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _list_3($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE customer = '%s' ORDER BY id DESC LIMIT 8";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function _exist($customer) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE customer = '%s'";
		$sql = sprintf($fmt, $this->tbl, $customer);
		echo $sql . "\n";
		$result = $db->query($sql);		
		if ($db->num_rows($result) > 0) {
			return true;
		}
		
		return false;		
	}
	
	function view_emp($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
	
		$ret = $this->_list_emp($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'mold/mold/_list');
		return true;
	}
	
	function view_customer($controller, $request) {
		$id = $request['id'];
	
		$ret = $this->_list_customer($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'mold/mold/_list_c');
		return true;
	}
	
	function view_supplier($controller, $request) {
		$id = $request['id'];
	
		$ret = $this->_list_supplier($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'mold/mold/_list_b');
		return true;
	}
	
	function temp($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s ";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$project = $this->_project($row['code']);
	
			$fmt = "UPDATE %s SET project = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $project, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
	
		logdate($controller, $request);
		return true;
	}
}
?>